//
//  MyCarSelectMenuViewController.m
//  SecondPage
//
//  Created by xiong qi on 13-5-13.
//  Copyright (c) 2013年 winston. All rights reserved.
//

#import "MyCarSelectMenuViewController.h"
#import "../../HondaPro_2/aejoy/Categories/Extensions+Honda.h"

#define CellHeight      50

@interface MyCarSelectMenuViewController ()

@end

@implementation MyCarSelectMenuViewController

+ (MyCarSelectMenuViewController *)sharedController {
    static MyCarSelectMenuViewController * s_sharedController = nil;
    @synchronized(s_sharedController) {
        if ([MyCarSelectMenuViewController invalid:s_sharedController]) {
            s_sharedController = [[MyCarSelectMenuViewController alloc] initWithNibName:nil bundle:nil];
        }
    }
    return s_sharedController;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        
        backgroundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(-20, -10, 380, 541)];
        [self.view addSubview:backgroundImageView];
        [backgroundImageView release];
        
        tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 340, 514)];
        [self.view addSubview:tableview];
        [tableview release];
        tableview.dataSource = self;
        tableview.delegate = self;
        [tableview setBackgroundView:[[UIView new] autorelease]];
        [tableview setBackgroundColor:[UIColor clearColor]];
        
        [self.view addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew context:nil];
        [self addObserver:self forKeyPath:@"from" options:NSKeyValueObservingOptionNew context:nil];
        [self addObserver:self forKeyPath:@"contentArray" options:NSKeyValueObservingOptionNew context:nil];
        [self addObserver:self forKeyPath:@"enableNilKey" options:NSKeyValueObservingOptionNew context:nil];
    }
    
    return self;
}

- (void)dealloc {
    [self.view removeObserver:self forKeyPath:@"frame"];
    [self removeObserver:self forKeyPath:@"from"];
    [self removeObserver:self forKeyPath:@"contentArray"];
    [self removeObserver:self forKeyPath:@"enableNilKey"];
    
    SafeRelease(_currentKey);
    SafeRelease(_currentValue);
    SafeRelease(_contentArray);
    
    [super dealloc];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (([keyPath isEqualToString:@"frame"] || [keyPath isEqualToString:@"from"]) && [UIView valid:self.view.superview]) {
        CGSize size = self.view.bounds.size;
        backgroundImageView.frame = CGRectMake(-15, -22, 30 + size.width, 44 + size.height);
        backgroundImageView.image = [[UIImage imageNamed:@"popview"] resizableImageWithCapInsets:UIEdgeInsetsMake(25, 25, 25, 60) resizingMode:UIImageResizingModeStretch];
        
        CGRect frameOfFrom = [self.view convertRect:self.from.bounds fromView:self.from];
        CGAffineTransform transform = CGAffineTransformIdentity;
        if (CGRectGetMinY(frameOfFrom) < size.height) {
            backgroundImageView.transform = CGAffineTransformIdentity;
            tableview.frame = CGRectMake(0, 7, size.width, size.height - 10);
        }
        else {
            transform = CGAffineTransformScale(transform, 1, -1);
            backgroundImageView.transform = transform;
            tableview.frame = CGRectMake(0, 7, size.width, size.height - 10);
        }
    }
    
    if ([keyPath isEqualToString:@"enableNilKey"]
        || [keyPath isEqualToString:@"contentArray"]) {
        [self resizingFrameOfSelectMenuView];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)reloadSelectMenuWithContentArray:(NSArray *)contentArray key:(NSString *)key value:(NSString *)value {
    self.currentKey = key;
    self.currentValue = value;
    self.contentArray = contentArray;
    
    [self resizingFrameOfSelectMenuView];
    
    [tableview reloadData];
}

#pragma mark
- (void)resizingFrameOfSelectMenuView {
    CGFloat count = self.contentArray.count;
    if (self.enableNilKey) {
        count += 1;
    }
    if (count > 6.5) {
        count = 6.5;
    }
    
    self.view.frame = CGRectMake(CGRectGetMinX(self.view.frame), CGRectGetMinY(self.view.frame), CGRectGetWidth(self.view.frame), CellHeight * count);
}

- (id)objectOfIndexPath:(NSIndexPath *)indexPath {
    NSUInteger index = indexPath.row;
    if (self.enableNilKey) {
        index -= 1;
    }
    
    return [self.contentArray nilOrObjectAtIndex:index];
}

- (NSString *)keyOfIndexPath:(NSIndexPath *)indexPath {
    id object = [self objectOfIndexPath:indexPath];
    
    if ([NSString valid:object]) {
        return object;
    }
    
    if ([NSDictionary validDictionary:object]) {
        return [object objectForKey:@"key"];
    }
    
    return nil;
}

- (NSString *)valueOfIndexPath:(NSIndexPath *)indexPath {
    id object = [self objectOfIndexPath:indexPath];
    
    if ([NSString valid:object]) {
        return object;
    }
    
    if ([NSDictionary validDictionary:object]) {
        return [object objectForKey:@"value"];
    }
    
    return nil;
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.contentArray.count + (self.enableNilKey ? 1 : 0);
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return CellHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"SelectCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell.backgroundColor = [UIColor clearColor];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleGray;
    cell.textLabel.font = [UIFont systemFontOfSize:12];
    cell.textLabel.textColor = [UIColor colorWithWhite:0.65 alpha:1];
    NSString * key = [self keyOfIndexPath:indexPath];
    if (([NSString invalidString:key] && [NSString invalidString:self.currentKey])
        || [self.currentKey isEqualToString:[self keyOfIndexPath:indexPath]]) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    cell.textLabel.text = [self valueOfIndexPath:indexPath];
    if ([NSString invalidString:cell.textLabel.text]) {
        cell.textLabel.text = @"< 空 >";
    }
    
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    self.currentKey = [self keyOfIndexPath:indexPath];
    self.currentValue = [self valueOfIndexPath:indexPath];
    
    [self dismissFromParentViewControllerWithCompletion:nil];
}

@end
